from django.shortcuts import render, HttpResponseRedirect, HttpResponse
from django.contrib.auth.hashers import make_password
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic.base import View
from users.forms import *
from course.models import Course, CourseResource, Video
from .models import *
from utils.sendEmail import *
import re
import hashlib


class IndexView(View):
    def get(self, request):
        user = request.user
        banners = Banner.objects.all()
        courses = Course.objects.all()
        print(banners)
        return render(request, "index.html", locals())


class CustomAuth(ModelBackend):
    # 根据用户名和邮箱条件返回
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        loginform = LoginForm(request.POST)
        if loginform.is_valid():
            username = request.POST.get("username", "")
            password = request.POST.get("password", "")
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return render(request, 'index.html')
                else:
                    return render(request, 'login.html', {"msg": "用户未激活"})
            else:
                return render(request, 'login.html', {"msg": "用户名或密码错误"})
        else:
            return render(request, 'login.html', {"login_form": loginform})


class LogoutView(View):
    def get(self, request):
        print(request.user.username)
        logout(request)
        return HttpResponseRedirect(reverse('index'))


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        registerForm = RegisterForm(request.POST)
        if registerForm.is_valid():
            register_form = RegisterForm()
            email = request.POST.get("email")
            oldUser = UserProfile.objects.filter(email=email)
            if oldUser.__len__() != 0:
                return render(request, 'register.html', {'msg': '邮箱已注册', 'register_form': register_form})
            password = request.POST.get("password")
            newUser = UserProfile()
            newUser.email = email
            newUser.password = make_password(password, None, 'pbkdf2_sha256')
            newUser.nick_name = email
            newUser.username = email
            newUser.is_active = False
            newUser.save()
            sendEmail(email, send_type="register")

            return HttpResponseRedirect(reverse('loginPage'))
        else:
            register_form = RegisterForm()
            return render(request, 'register.html', {"reg_form": registerForm, 'register_form': register_form})


class findPwdBackView(View):
    def get(self, request):
        pwdBackForm = PwdBackForm()
        return render(request, 'forgetpwd.html', {'pwdBack_form': pwdBackForm})

    def post(self, request):
        pwdBackForm = PwdBackForm(request.POST)
        if pwdBackForm.is_valid():
            email = request.POST.get("email")
            oldUser = UserProfile.objects.filter(email=email)
            if oldUser.__len__() == 0:
                return render(request, 'forgetpwd.html', {'msg': '邮箱不存在', 'pwdBack_form': pwdBackForm})
            else:
                print("stage1")
                user = oldUser[0]
                email = user.email
                sendEmail(email, send_type="getPwdBack")
                return HttpResponseRedirect(reverse('loginPage'))
        else:
            return render(request, 'forgetpwd.html', {'pwdBack_form': pwdBackForm})


def infoCenter(request):
    user = request.user
    print(user.gender)
    return render(request, 'usercenter-info.html', {'user': user})


def editInfo(request):
    user = request.user
    editInfoForm = EditInfoForm(request.POST)
    birthday = request.POST.get("birthday")
    if birthday.find('-') == -1:
        birthday = user.birthday
    nick_name = request.POST.get("nick_name")
    gender = request.POST.get("gender")
    address = request.POST.get("address")
    mobile = request.POST.get("mobile")
    if editInfoForm.is_valid():

        user.nick_name = nick_name
        user.birthday = birthday
        user.gender = gender
        user.address = address
        user.mobile = mobile
        try:
            user.save()
        except Exception as e:
            user.birthday = '1970-1-1'
            user.save()

    return HttpResponseRedirect(reverse('infoCenter'))


class UploadImageView(View):
    def post(self, request):
        image_form = UploadImageForm(request.POST, request.FILES, instance=request.user)
        if image_form.is_valid():
            image_form.save()

        return HttpResponse("ok")


def emailVerify(request, code):
    print(code)
    evr = EmailVerifyRecord.objects.filter(code=code)
    if evr.__len__() != 0:
        email = evr[0].email
        userToActivate = UserProfile.objects.get(email=email)
        userToActivate.is_active = True
        userToActivate.save()
        return render(request, 'login.html', {"msg": "用户激活成功"})
    else:
        return render(request, 'register.html', {'msg': '用户激活失败'})


def pwdBackVerify(request, code):
    print(code)
    evr = EmailVerifyRecord.objects.filter(code=code)
    if evr.__len__() != 0:
        print("pwdbkvy in")
        email = evr[0].email
        user = UserProfile.objects.get(email=email)
        email = user.email
        return render(request, 'password_reset.html', {"email": email})
    else:
        return render(request, 'forgetpwd.html', {'msg': '找回密码验证失败'})


def pwdReset(request):
    email = request.POST.get("email")
    password = request.POST.get("password")
    user = UserProfile.objects.filter(email=email)[0]
    user.password = make_password(password, None, 'pbkdf2_sha256')
    user.save()
    return HttpResponseRedirect(reverse('loginPage'))


def alterEmail(request):
    print("emailIn")
    emailForm = AlterEmailForm(request.POST)
    if emailForm.is_valid():
        newEmail = request.POST.get("email")
        print(newEmail)
        user = request.user
        email = user.email
        sendEmail(email, send_type="alterEmail", new_email=newEmail)
        logout(request)
        return HttpResponseRedirect(reverse("index"))
    else:
        return HttpResponseRedirect(reverse("infoCenter"))


def alterEmailVerify(request, code, newEmail):
    print(code)
    print(newEmail)
    evr = EmailVerifyRecord.objects.filter(code=code)
    if evr.__len__() != 0:
        newcode = code = hashlib.md5(str(newEmail + "alterEmail").encode('utf-8')).hexdigest()[-10:]
        newcode = str(newcode)
        newcode = newcode.replace("/", "*")
        if newcode == code:
            newEmailUser = UserProfile.objects.filter(email=newEmail)
            if newEmailUser.__len__() == 0:
                email = evr[0].email
                user = UserProfile.objects.get(email=email)
                user.email = newEmail
                user.save()
            else:
                return render(request, 'login.html', {'msg': '新绑定邮箱已被占用'})
            return render(request, 'login.html', {'msg': '邮箱修改完成请重新登录'})
        else:
            return render(request, 'login.html', {'msg': '邮箱修改失败'})
    else:
        return render(request, 'login.html', {'msg': '邮箱修改失败'})